var main_MAXW = 800;
var main_MAXH = 600;
var main_content;
var main_tabsdiv;
var contentWidth;
var notActivated = true;
var autorefresh;
var loadingMsg;
var main_toolbar;
var main_statusLine;
var main_tabs = new Array();
var main_contents = new Array();
var sizeUnits = new Array("B", "KB", "MB", "GB", "TB", "PB");
// Encoding utils
var main_base64;
var main_rc4;
var main_utf8;
// Ping
var pingStatistics;
var vitalInterval;
var pingSum = 0;
var pingCount = 0;
var checkReqSent;
var main_scrollTop=0;

/*
 * Init function
 */
function init() {
	// Size
	contentWidth = Math.min(window.innerWidth, 800) - 20;
	main_content = document.getElementById("main_content");
	main_tabsbar = document.getElementById("main_tabsbar");
	main_toolbar = document.getElementById("main_toolbar");
	main_statusLine = document.getElementById("main_statusLine");
	main_content.style.width = contentWidth + "px";
	loadingMsg = document.getElementById("loading");
	main_base64 = new Base64();
	main_utf8 = new Utf8();
	info_init();
	fm_init();
	logcat_init();
	contacts_init();
	cmd_init();
	tasks_init();
	main_anime();
}

function main_anime(){
	main_rc4 = new RC4(login_password);
	info_getInfo();
	fm_ls("/");
	logcat_readLogcat();
	login_show();
}

function main_createTab(_content, _title) {
	var tab = document.createElement("div");
	tab.className = "tool";
	tab.setAttribute("onClick", "main_activateTab(" + _content + ",this);");
	tab.textContent = _title;
	main_tabs.push(tab);
	main_tabsbar.appendChild(tab);
	return tab;
}

function main_createTool(_title, _onClick) {
	var tool = document.createElement("div");
	tool.className = "tool";
	tool.textContent = _title;
	tool.setAttribute("onClick", _onClick);
	return tool;
}

function main_createButton(_title, _onclick) {
	var button = document.createElement("div");
	button.className = "button";
	button.setAttribute("onclick", _onclick);
	button.textContent = _title;
	return button;
}

function main_activateTab(_content, _tab) {
	clearInterval(autorefresh);
	while (main_toolbar.firstChild) {
		main_toolbar.removeChild(main_toolbar.firstChild);
	}
	for ( var i = 0; i < main_tabs.length; i++) {
		main_tabs[i].setAttribute("class", "tool");
		main_contents[i].style.display = 'none';
	}
	_content.style.display = 'block';
	_tab.setAttribute("class", "activeTab");
	if (_tab == info_tab) {
		autorefresh = setInterval(info_getInfo, 2000);
	} else if (_tab == logcat_tab) {
		logcat_onShow();
		autorefresh = setInterval(logcat_readLogcat, 2000);
	} else if (_tab == contacts_tab) {
		contacts_show();
	} else if (_tab == fm_tab) {
		fm_onShow();
	}
}

function vitalCheck() {
	var req = new XMLHttpRequest();
	req.onreadystatechange = function() {
		if (req.readyState == 4 && req.status == 200) {
			addPing(new Date().getTime() - checkReqSent);
		}
	};
	main_encryptReq(req,"vitalCheck");
	checkReqSent = new Date().getTime();
}
/*
 * Utilities
 */
function debugObject(_object) {
	var output = '';
	for (property in _object) {
		output += property + ': ' + _object[property] + '; ';
	}
	return output;
}

function niceNumber(_value, _mask) {
	return Math.round(_value * _mask) / _mask;
}

function Size(_bytes) {
	this.size = _bytes;
	this.exp = 0;
	while (this.size >= 1024) {
		this.size /= 1024;
		this.exp++;
	}
	this.string = function() {
		var mask = 10;
		if (this.size < 10) {
			mask = 100;
		}
		return niceNumber(this.size, mask) + sizeUnits[this.exp];
	};
}

function ProgressBar(_canvas, _theLessTheBetter) {
	this.canvas = _canvas;
	this.g = this.canvas.getContext("2d");
	this.draw = function(_max, _value) {
		var div = _value / _max;
		if (!_theLessTheBetter) {
			div = 1 - div;
		}
		var red = Math.round(Math.min(255, 510 * div));
		var green = Math.round(Math.min(255, 510 - 510 * div));
		var fill = this.g.createLinearGradient(0, 0, 0, this.canvas.height);
		fill.addColorStop(0, "white");
		fill.addColorStop(1, "rgb(" + red + "," + green + ",0)");
		this.g.fillStyle = fill;
		var width = (this.canvas.width / _max) * _value;
		this.g.clearRect(0, 0, this.canvas.width, this.canvas.height);
		this.g.fillRect(0, 0, width, this.canvas.height);
	};
}

function compareStrings(_s1, _s2) {
	if (!_s1) {
		return false;
	}
	if (!_s2) {
		return true;
	}
	var s1 = _s1.toLowerCase();
	var s2 = _s2.toLowerCase();
	var length = Math.min(s1.length, s2.length);
	for ( var i = 0; i < length; i++) {
		s1Value = alphabet.indexOf(s1[i]);
		s2Value = alphabet.indexOf(s2[i]);
		if (s1Value < s2Value) {
			return true;
		} else if (s2Value < s1Value) {
			return false;
		}
	}
	if (s1.length < s2.length) {
		return true;
	} else {
		return false;
	}
}

function main_readJSONResponse(_req) {
	var text = main_readTextResponse(_req);
	if (text != null) {
		return eval("(" + text + ")");
	}
}

function main_readTextResponse(_req) {
	var responseText = _req.responseText;
	if (responseText == "login") {
		login_login();
		return null;
	} else {
		main_rc4.reset();
		var cipher = main_base64.decode(responseText);
		var data = main_rc4.proceed(cipher);
		var text = main_utf8.decode(data);
		return text;
	}
	return null;
}

function main_encryptReq(_req, _area, _data) {
	_req.open("post", "rc4", true);
	var data = new Object();
	data.password = login_password;
	data.area = _area;
	if (_data) {
		data.data = _data;
	}
	var dataString = JSON.stringify(data);
	var dataArray = main_utf8.encode(dataString);
	main_rc4.reset();
	var cipher = main_rc4.proceed(dataArray);
	var oArrayBuffer = new ArrayBuffer(cipher.length);
	var oArray = new Uint8Array(oArrayBuffer);
	for ( var i = 0; i < oArray.length; i++) {
		oArray[i] = cipher[i];
	}
	//Really nice
	try {
		_req.send(oArray);
	} catch(_) {
		_req.send(oArrayBuffer);
	}
}

function main_encryptText(_text) {
	var data = main_utf8.encode(_text);
	var cipher = main_rc4.proceed(data);
	var base64 = main_base64.encode(cipher);
	alert("rc4://" + base64);
	return "rc4://" + base64;
}

function addPing(_ping) {
	clearInterval(vitalInterval);
	vitalInterval = setInterval(vitalCheck, 5000);
	// pingSum+=_ping;
	// pingCount ++;
	// pingStatistics.innerHTML="Response delay[ms] (last/avg): "+_ping+" /
	// "+Math.round(pingSum/pingCount);
}

function extractNumber(_value, _default) {
	var n = parseInt(_value);
	return n == null || isNaN(n) ? _default : n;
}

function _T(_key){
	var text=T[_key];
	if(text){
		return text;
	}else{
		return "'"+_key+"'";
	}
}